package com.hm.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hm.reggie.common.R;
import com.hm.reggie.dto.SetmealDto;
import com.hm.reggie.entity.Setmeal;
import com.hm.reggie.entity.SetmealDish;
import com.hm.reggie.service.CategoryService;
import com.hm.reggie.service.SetMealDishService;
import com.hm.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanMetadataAttribute;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetMealController {
    @Autowired
    private SetMealDishService setMealDishService;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;


    /***
     * http://localhost:8080/setmeal/page?page=1&pageSize=10&name=%E5%93%88%E5%93%88%E5%93%88
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //创建page对象
        Page<Setmeal> setMealPage = new Page<Setmeal>(page,pageSize);
        //构造条件
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null,Setmeal::getName,name);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        //执行分页查询
        setmealService.page(setMealPage,queryWrapper);

        //把setmeal的page对象拷贝给setmealdto的page
        //创建setmealdto的page对象
        Page<SetmealDto> setmealDtoPage = new Page<>(page,pageSize);
        //把分页信息传给setmealDtoPage,records数组单独封装,records里面就是分页的具体数据
        BeanUtils.copyProperties(setMealPage,setmealDtoPage,"records");
        //处理records，其实就是把categoryName写进去，setmealDishes没用
        List<Setmeal> setmealList = setMealPage.getRecords();
        List<SetmealDto> records = new ArrayList<>();
        log.info("setmeal-record长度:"+setmealList.size());
        for (Setmeal setmeal:setmealList){
            //遍历对象，把categoryName写进去
            String categoryName= categoryService.getById(setmeal.getCategoryId()).getName();
            log.info("categoryName:"+categoryName);
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal,setmealDto);
            setmealDto.setCategoryName(categoryName);
            //把setmealdish也顺便塞进去吧
            LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SetmealDish::getSetmealId,setmeal.getId());
            List<SetmealDish> list = setMealDishService.list(lambdaQueryWrapper);
            setmealDto.setSetmealDishes(list);
            log.info("setmealDto:"+setmealDto.toString());
            //把dto对象塞进集合
            records.add(setmealDto);
        }
        setmealDtoPage.setRecords(records);

        return R.success(setmealDtoPage);
    }

    /***
     * http://localhost:8080/setmeal
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCach",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("待添加的数据："+setmealDto.toString());
        setmealService.saveSetmealWithDish(setmealDto);
        return R.success("添加成功");
    }

    /***
     *
     * http://localhost:8080/setmeal?ids=1718533567145836545,1718530377419677697
     * 获取参数方法：(@RequestParamLong[] ids)
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCach",allEntries = true)
    public R<String> delete(@RequestParam Long[] ids){
        //log.info();
        //判断是否是停售状态

        setmealService.removeWithDishByIds(ids);
        return R.success("删除成功");
    }

    /***
     * http://localhost:8080/setmeal/status/0?ids=1415580119015145474
     * 参数接受方法：    @PostMapping("/status/{status}")    (@PathVariable int status,Long[] ids)
     * 起售：1    停售：0
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable int status,Long[] ids){
        String re = "";
        if (status == 1){
            re = "已起售";
        } else {
            re = "已停售";
        }
        setmealService.updateSetmealStatusByIds(status,ids);
        return R.success(re);
    }


    /***
     * http://localhost:8080/setmeal/1415580119015145474
     * 参数获取方法：@GetMapping("/{id}")    (@PathVariable Long id)
     * 获取setmeal对象
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> get(@PathVariable Long id){
        log.info("需要修改的setmeal的id是："+id);
        SetmealDto setmealDto = new SetmealDto();
        //获取到setmeal对象
        Setmeal setmeal = setmealService.getById(id);
        BeanUtils.copyProperties(setmeal,setmealDto);
        //获取到setmealdish数组
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(id != null,SetmealDish::getSetmealId,id);
        List<SetmealDish> setmealDishes = setMealDishService.list(queryWrapper);
        //组装到dto对象
        setmealDto.setSetmealDishes(setmealDishes);
        return R.success(setmealDto);
    }

    /***
     * http://localhost:8080/setmeal
     * 接受参数方法： 前端穿json   (@RequestBody SetmealDto setmealDto)
     * 更新dto对象
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "setmealCach",allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto){
        //先修改setmeal对象
        setmealService.updateById(setmealDto);
        //删除原有的setmealdish数据
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmealDto.getId() != null,SetmealDish::getSetmealId,setmealDto.getId());
        setMealDishService.remove(queryWrapper);
        //重新插入新的setmealdish数据
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish:setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setMealDishService.saveBatch(setmealDishes);
        //setmealDto.setSetmealDishes(setmealDishes);

        return R.success("修改成功！");
    }


    /***
     * ?categoryId=1413342269393674242&status=1
     * 这种情况也可以用实体类直接接收
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCach",key = "#categoryId+'-'+#status")
    public R<List<Setmeal>> getList(Integer status,Long categoryId){
        log.info("categoryId是{},状态是{}",categoryId,status);
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(categoryId != null,Setmeal::getCategoryId,categoryId);
        queryWrapper.eq(status != null,Setmeal::getStatus,status);
        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }

}
